<template>
  <view
    class="switch switch--base"
    :class="[{ 'switch--open': value, 'switch--close': !value, 'switch--disabled': disabled }]"
    :style="[getStyle]"
    @click="handleClick"
  >
    <view class="switch__button">
      <view v-show="!value" class="close-line"></view>
      <template v-if="activeText">
        <view v-show="value" class="switch__label open">{{ activeText }}</view>
        <view v-show="!value" class="switch__label close">{{ inactiveText }}</view>
      </template>
    </view>
  </view>
</template>

<script lang="ts">
import { defineComponent, computed } from '@vue/composition-api'

export default defineComponent({
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    activeColor: {
      type: String,
      default: '',
    },
    inactiveColor: {
      type: String,
      default: '',
    },
    activeText: {
      type: String,
      default: '',
    },
    inactiveText: {
      type: String,
      default: '',
    },
  },
  emits: ['change', 'input'],
  setup(props, { emit }) {
    const getStyle = computed(() => {
      return {
        backgroundColor: props.value ? props.activeColor : props.inactiveColor,
      }
    })

    const handleClick = (event: Event) => {
      if (props.disabled) return
      emit('input', !props.value)
      emit('change', !props.value, event)
    }

    return {
      getStyle,
      handleClick,
    }
  },
})
</script>
<style lang="scss" scoped>
.switch {
  cursor: pointer;
  display: flex;
  align-items: center;
  background-color: $--primary-c;
  border-radius: 42rpx;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center center;
  flex: 0 0 auto; // 防止被压缩
  &--close {
    background-color: #ebebeb;
    // .close-line {
    //   background: #f0f0f0;
    //   border-radius: 4rpx;
    // }
  }
  .switch__button {
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background: $--white-c;
    transition: transform 0.3s;
    .switch__label {
      color: $--white-c;
      @include fz24;
      &.open {
        transform: translateX(-40rpx);
        min-width: 35px;
      }
      &.close {
        transform: translateX(64rpx);
        min-width: 35px;
      }
    }
  }
  &.switch--disabled {
    opacity: 0.6;
  }
  &.switch--base {
    width: 120rpx;
    height: 50rpx;
    line-height: 50rpx;
    .switch__button {
      height: 26rpx;
      width: 26rpx;
      transform: translateX(30%);
    }
    &.switch--open {
      .switch__button {
        transform: translateX(325%);
      }
    }
    &.switch--close {
      .close-line {
        width: 16rpx;
        height: 4rpx;
      }
    }
  }
}
</style>
